<template>
  <a-modal
    title="新增数据"
    width="800px"
    :visible="visible"
    centered
    :maskClosable="false"
    @cancel="handleCancel"
  >
    <div class="modal-steps">
      <a-steps :current="current" type="navigation" size="small">
        <a-step v-for="item in steps" :key="item.key" :title="item.title" />
      </a-steps>
    </div>
    <div class="modal-content">
      <div class="modal-upload" v-show="current === 0">
        <upload ref="upload" @success="handleUploadSuccess" :accept="accept"/>
      </div>

      <div class="modal-parse" v-show="current === 1">
        <div class="percent-wrapper" v-show="!tableVisible">
          <a-spin tip="正在解析数据..." :spinning="spinning">
            <a-icon slot="indicator" type="loading-3-quarters" style="font-size: 36px" spin />
          </a-spin>
          <span>
            <span v-if="!spinning && currentRecord && currentRecord.status === 3">
              <a-icon type="check-circle" style="font-size: 36px; color: #52c41a;"/><br>
              <span style="color: #52c41a;">解析数据完成</span>
            </span>
            <span v-if="!spinning && currentRecord && currentRecord.status === 4">
              <a-icon type="exclamation-circle" style="font-size: 36px; color: #f5222d;"/><br>
              <span style="color: #f5222d;">解析数据失败，请检查文件</span>
            </span>
          </span>
        </div>
        <upload-data-table :visible="current === 1 && tableVisible" ref="dataTable"/>
      </div>

      <div class="modal-save" v-show="current === 2">
        <define-data ref="defineData"/>
      </div>

      <div class="modal-save" v-show="current === 3">
        <div class="percent-wrapper">
          <a-progress :percent="savePercent" :status="savePercentStatus" />
          <span v-if="savePercentStatus === 'exception'" class="temp-exception">{{ saveException }}</span>
          <span v-if="savePercentStatus === 'success'" class="temp-reupload"><a @click="continueUpload">继续上传</a></span>
        </div>
      </div>
    </div>

    <div slot="footer">
      <a-button v-if="current === 0" @click="handleCancel">取消</a-button>
      <a-button v-if="current === 1" type="primary" @click="nextStep">下一步</a-button>
      <a-button v-if="current === 2" type="primary" @click="preStep">上一步</a-button>
      <a-button v-if="current === 2" type="primary" @click="saveTable">保存</a-button>
    </div>
  </a-modal>
</template>

<script>
import _ from 'lodash'
import { timeSpaceDataRecordAdd, parseIndexFile, timeSpaceDataRecordDetail } from '@/api/modular/main/tsdatarecord/timeSpaceDataRecordManage'
import upload from '@/views/main/tsdatarecord/upload'
import uploadDataTable from '@/views/main/biindexdata/modal/uploadDataTable'
import defineData from '@/views/main/biindexdata/modal/defineData'
const KB = 1024
const MB = 1024 * 1024
const GB = 1024 * 1024 * 1024
export default {
  name: 'uploadModal',
  components: {
    upload,
    uploadDataTable,
    defineData
  },
  data() {
    return {
      accept: '.xls,.xlsx,.csv,.zip',
      visible: false,
      current: 0,
      percent: 0,
      percentStatus: 'active', // success exception normal active
      progressVisible: false,
      steps: [
        {
          key: 0,
          title: '上传文件'
        },
        {
          key: 1,
          title: '解析数据'
        },
        {
          key: 2,
          title: '完成导入'
        }
      ],
      templateException: '',
      fileName: '',
      columns: [
        {
          title: '序号',
          align: 'center',
          width: 50,
          dataIndex: 'index'
        },
        {
          title: '我方文号',
          align: 'left',
          width: 150,
          dataIndex: 'ownRecordNumber',
          scopedSlots: { customRender: 'ownRecordNumber' }
        },
        {
          title: '提案名称',
          align: 'left',
          dataIndex: 'preTitle',
          scopedSlots: { customRender: 'preTitle' }
        },
        {
          title: '申请类型',
          align: 'center',
          width: 120,
          dataIndex: 'applyType',
          scopedSlots: { customRender: 'applyType' }
        },
        {
          title: '客户名称',
          align: 'left',
          dataIndex: 'customerName',
          scopedSlots: { customRender: 'customerName' }
        },
        {
          title: '客户状态',
          align: 'center',
          width: 80,
          dataIndex: 'customerId',
          scopedSlots: { customRender: 'customerId' }
        },
        {
          title: '操作',
          align: 'center',
          width: 60,
          scopedSlots: { customRender: 'action' }
        }
      ],
      tableData: [],
      savePercent: 0,
      savePercentStatus: 'active', // success exception normal active
      saveException: '',
      customerCache: {},
      spinning: false,
      parseTimer: null,
      currentRecord: null,
      tableVisible: false
    }
  },
  created() {

  },
  destroyed() {
    this.clearParseTimer()
  },
  watch: {
    current(s) {
      this.stepChange()
    }
  },
  methods: {
    stepChange() {
      if (this.current === 1 && this.currentRecord) {
        this.tableVisible = false
        this.parseTimer = setInterval(() => {
          if (this.currentRecord.status === 3 || this.currentRecord.status === 4) {
            this.spinning = false
            this.$emit('parseComplete')
            this.clearParseTimer()
            if (this.currentRecord.status === 3) {
              setTimeout(() => {
                this.tableVisible = true
                this.$refs.dataTable.init(this.currentRecord.id)
              }, 700)
            }
          } else {
            timeSpaceDataRecordDetail(this.currentRecord).then(res => {
              if (res.success) {
                this.currentRecord = res.data
              } else {
                this.clearParseTimer()
              }
            }).catch(() => {
              this.clearParseTimer()
            })
          }
        }, 3000)

      } else {
        this.clearParseTimer()
      }
    },
    clearParseTimer() {
      if (this.parseTimer) {
        clearInterval(this.parseTimer)
        this.parseTimer = null
      }
    },
    handleUploadSuccess(result) {
      console.log(result)
      const body = {
        title: result.fileName,
        size: result.size,
        sizeInfo: this.buildSizeInfo(result.size),
        extension: result.fileType,
        filePath: result.filePath,
        identifier: result.identifier,
        status: 0
      }
      const _that = this
      timeSpaceDataRecordAdd(body).then(res => {
        if (res.success) {
          _that.currentRecord = res.data
          setTimeout(() => {
            _that.current = 1
            _that.spinning = true
            parseIndexFile(res.data)
          }, 700)
          this.$emit('ok')
        }
      })
    },
    buildSizeInfo(size) {
      let info
      if (size < KB) {
        info = size + ' b'
      } else if (size < (MB)) {
        info = _.ceil(_.divide(size, KB), 2) + ' Kb'
      } else if (size < (GB)) {
        info = _.ceil(_.divide(size, MB), 2) + ' Mb'
      } else {
        info = _.ceil(_.divide(size, GB), 2) + ' Gb'
      }
      return info
    },
    reUpload() {
      this.progressVisible = false
      this.fileName = ''
      this.percent = 0
      this.percentStatus = 'active'
      this.templateException = ''
      this.savePercent = 0
      this.savePercentStatus = 'active'
      this.saveException = ''
      this.tableData = []
      this.current = 0
      this.currentRecord = null
      this.clearXlsxTable()
      this.$refs.upload.reset()
    },
    clearXlsxTable() {
    },
    customRequest(data) {
      this.progressVisible = true
      this.fileName = data.file.name
      this.percent = 10
      console.log(data)
      const e = {
        target: {
          files: []
        }
      }
      this.percent = 20
      e.target.files.push(data.file)
      this.percent = 25
    },
    init() {
      this.current = 0
      this.visible = true
    },
    editTableData(record) {
      record.edit = true
    },
    editDone(record) {
      record.edit = false
    },
    handleCancel() {
      this.visible = false
      this.reUpload()
    },
    rejectNotAccept(fileList) {
      console.log(fileList)
      const file = fileList[0]
      const type = file ? file.type : ''
      this.$message.warning('上传的' + type + '类型不支持上传')
    },
    preStep() {
      this.current--
    },
    nextStep() {
      this.current++
      this.$refs.defineData.init(this.currentRecord)
    },
    saveTable() {
      this.$refs.defineData.doSave()
    },
    checkInputContent(text) {
      return !text || text === ''
    },
    continueUpload() {
      this.reUpload()
    },
    customerNameChange(e, record) {
      console.log('e:', e)
      console.log('record:', record)
    }
  }
}
</script>

<style scoped lang="less">
  .ant-upload-drag-icon {
    margin: 29px 0 20px 0;
  }
  .modal-upload {
    padding: 10px 0;
  }
  .modal-parse {
    padding: 10px 0;
  }
  .modal-table {
    padding: 10px 0;
  }
  .modal-save {
    padding: 0 5px;
    max-height: 400px;
    overflow-y: auto;
    margin: 10px 0;
  }

  p.download-link {
    margin-bottom: 30px;
  }

  .percent-wrapper {
    background: #fafafa;
    border: 1px dashed #d9d9d9;
    border-radius: 2px;
    padding: 93px 50px 94px;
    text-align: center;
  }

  .file-name {
    color: rgba(0, 0, 0, 0.4);
  }

  .temp-exception {
    color: red;
    font-size: 12px;
  }

  span.temp-reupload {
    margin-left: 10px;
    font-size: 12px;
  }

  ::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }

  ::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    //background-color: #8c8c8c;
    background-color: rgba(0, 0, 0, 0.25);
  }

  ::-webkit-scrollbar-track {
    background-color: #f6f6f6;
  }
  ::-webkit-scrollbar-thumb,
  ::-webkit-scrollbar-track {
    border: 0;
  }
</style>
